/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bizentity.json.operation;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.operation.TccAction;
import com.inspur.edp.bef.bizentity.operation.internalmgraction.TccSettingElement;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;
import com.inspur.edp.das.commonmodel.json.CommonModelNames;

public class TccSettingElementSerializer extends JsonSerializer<TccSettingElement> {

  protected boolean isFull = true;

  public TccSettingElementSerializer() {
  }

  public TccSettingElementSerializer(boolean full) {
    isFull = full;
  }

  @Override
  public void serialize(TccSettingElement value, JsonGenerator gen,
      SerializerProvider serializers) {
    SerializerUtils.writeStartObject(gen);
    writeProperty(value, gen);
    SerializerUtils.writeEndObject(gen);
  }

  private void writeProperty(TccSettingElement ele, JsonGenerator writer) {
    SerializerUtils.writePropertyValue(writer, CommonModelNames.ID, ele.getID());
    SerializerUtils.writePropertyValue(writer, CommonModelNames.Code, ele.getCode());
    SerializerUtils.writePropertyValue(writer, CommonModelNames.Name, ele.getName());
    writeTriggerFields(writer, ele);
    writeTccAction(writer, ele.getTccAction());
  }

  private void writeTriggerFields(JsonGenerator writer, TccSettingElement ele) {
    SerializerUtils.writePropertyName(writer, BizEntityJsonConst.TriggerFields);
    SerializerUtils.WriteStartArray(writer);
    // [
    if (ele.getTriggerFields().size() > 0) {
      for (String item : ele.getTriggerFields()) {
        SerializerUtils.writePropertyValue_String(writer, item);
      }
    }
    // ]
    SerializerUtils.WriteEndArray(writer);
  }

  private void writeTccAction(JsonGenerator writer, TccAction action) {
    if (action == null) {
      return;
    }
    try {
      SerializerUtils.writePropertyName(writer, BizEntityJsonConst.TccAction);
      getConvertor().serialize(action, writer, null);
    } catch (Exception e) {
      throw new RuntimeException("TCC动作序列化异常" + action.getCode(), e);
    }
  }

  protected TccActionSerializer getConvertor() {
    return new TccActionSerializer(isFull);
  }
}
